package com.easylinkin.linkappapi.common.service;

import cn.hutool.core.collection.CollectionUtil;
import com.easylinkin.linkappapi.common.utils.message.AppSendMessageUtil;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage.type;
import com.easylinkin.linkappapi.lobar.service.WarningNotifierService;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2022/10/24
 * @description
 */
@Slf4j
@Service
public class AppSendMessageServiceImpl implements AppSendMessageService {

  @Autowired
  private LinkappUserService userService;

  @Autowired
  private AppSendMessageUtil appSendMessageUtil;

  @Autowired
  private WarningNotifierService warningNotifierService;

  @Override
  public void pushMessageToPhone(String id, Integer modelId, Integer type, String userId,
      String title, String content) {
    try {
      LinkappUser linkappUser = userService.get(Long.parseLong(userId));
      if(null == linkappUser){
        log.info("pushMessageToPhone 用户id = {} 极光推送失败 原因：找不到用户",userId);
        return;
      }
      if(StringUtils.isEmpty(linkappUser.getPhone())){
        log.info("pushMessageToPhone 用户id = {} 极光推送失败 原因：缺少手机号",userId);
        return;
      }
      AppSendMessage appSendMessage = new AppSendMessage();
      appSendMessage.setBusinessId(id);
      appSendMessage.setContent(content);
      appSendMessage.setType(type);
      appSendMessage.setModelId(modelId);
      appSendMessage.setPhone(linkappUser.getPhone());
      appSendMessage.setTenantId(linkappUser.getTenantId());
      appSendMessage.setTitle(title);
      appSendMessageUtil.sendAppMessage(appSendMessage);
    } catch (Exception e){
      log.error("pushMessageToPhone 用户id = {} 极光推送失败 原因：{}",userId,e.getMessage());
    }
  }

  @Override
  public void sendAppWarning(String id, Integer warningType, String msgContent, String tenantId) {
    List<String> userIds = warningNotifierService.findNotifiersByWarningTypesAndTenantId(warningType,tenantId);
    if(CollectionUtil.isNotEmpty(userIds)&&StringUtils.isNotEmpty(msgContent)){
      userIds.forEach(p->pushMessageToPhone(id, warningType, type.WARNING, p ,"劳务异常预警", msgContent));
    }
  }
}
